//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "tmf\client\fn_ammoBoxFill.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);


// The 1000 here ensures we call the last handler only. If no handler is executed, we default to the normal box filling
if (count (["MSO","FillAmmoBox",_this] call ioc_fnc_exec) <= 0) then {
	_this spawn {
		private ["_box","_key","_content","_type","_count","_content_name","_extra"];
		DEFAULT_PARAM(_box,0,objNull);
		DEFAULT_PARAM(_key,1,"");
		DEFAULT_PARAM(_extra,2,[]);
		
		_content_name = "";
		_content = nil;
		waituntil { !isnil QUOTE(WEST_AMMO_BOX_CONTENT) && !isnil QUOTE(EAST_AMMO_BOX_CONTENT) && {(count WEST_AMMO_BOX_CONTENT > 0)} && {(count EAST_AMMO_BOX_CONTENT > 0)}};
		
		if (IS_OBJECT(_box) && {!(isNull _box)}) then {
			if !(IS_STRING(_key)) then { _key = str(_key); };
			if (_key == "") then { _key = str(playerSide); };
			
			switch (toupper(_key)) do {
				case "EAST": { _content = EAST_AMMO_BOX_CONTENT };
				case "WEST": { _content = WEST_AMMO_BOX_CONTENT };
				default {
					_content_name = Format["%1_AMMO_BOX_CONTENT",toupper(_key)];
					if (isnil _content_name) then {
						_content_name = switch (toUpper(str(playerSide))) do {
							case "EAST":{ "EAST_AMMO_BOX_CONTENT" };
							default { "WEST_AMMO_BOX_CONTENT" };
						};
					};
					_content = missionNameSpace getVariable [_content_name, []];
				};
			};

			if (!isnil "_content") then {
				if (count _extra > 0) then {
					_content = [_content, _extra] call TFUNC(arrayPushStack);
				};
				if (count _content > 0) then {
					clearMagazineCargo _box;
					clearWeaponCargo _box;
					clearItemCargo _box;
					clearBackpackCargo _box;
					{
						_type = _x select 0;
						_name = _x select 1;
						_count = _x select 2;
						If (_type == 1) then {
							_box addWeaponCargo [_name,_count];
						};
						If (_type == 0) then {
							_box addMagazineCargo [_name,_count];
						};
						If (_type == 2) then {
							_box addItemCargo [_name,_count];
						};
						If (_type == 3) then {
							_box addBackpackCargo [_name,_count];
						};
					} foreach _content;
				};
			};
		};
		TRACE("End Spawned");
	};
};
TRACE("End");